<template>
  <div class="category-management">
    <!-- 顶部导航栏 -->
    <div class="nav-tabs">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="类别" name="category"></el-tab-pane>
        <el-tab-pane label="客户" name="customer"></el-tab-pane>
        <el-tab-pane label="供应商" name="supplier"></el-tab-pane>
        <el-tab-pane label="商品" name="product"></el-tab-pane>
        <el-tab-pane label="支出" name="expense"></el-tab-pane>
        <el-tab-pane label="收入" name="income"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="action-bar">
      <div class="search-area">
        <el-input
          v-model="searchQuery"
          placeholder="输入类别名称查询"
          clearable
          class="search-input"
        />
        <el-select
          v-model="statusFilter"
          placeholder="显示启用类别"
          class="status-select"
        >
          <el-option label="全部" value="all"></el-option>
          <el-option label="已启用" value="enabled"></el-option>
          <el-option label="已禁用" value="disabled"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="showAddDialog">新增</el-button>
        <el-button @click="handleDisable">禁用</el-button>
        <el-button @click="handleEnable">启用</el-button>
        <el-button @click="refreshData">刷新</el-button>
      </div>
    </div>

    <!-- 类别表格 -->
    <div class="category-table">
      <el-table
        :data="filteredCategories"
        style="width: 100%"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="类别" width="300">
          <template #default="scope">
            <span v-if="scope.row.level === 1">{{ scope.row.name }}</span>
            <span v-if="scope.row.level === 2">|- {{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="enabled"
              inactive-value="disabled"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalItems"
        layout="prev, pager, next"
      ></el-pagination>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="showDialog"
      width="500px"
    >
      <el-form :model="categoryForm" :rules="formRules" ref="categoryFormRef">
        <el-form-item label="上级分类：" prop="parentId">
          <el-select
            v-model="categoryForm.parentId"
            placeholder="请选择上级分类"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="category in parentCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="*类别：" prop="name" required>
          <el-input v-model="categoryForm.name" placeholder="请输入类别名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'CategoryManagement',
  setup() {
    // 导航栏
    const activeTab = ref('product')

    // 搜索和筛选
    const searchQuery = ref('')
    const statusFilter = ref('enabled')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalItems = ref(18)
    const selectedCategories = ref([])

    // 类别数据
    const categories = reactive([
      { id: 1, name: '酒', level: 1, status: 'enabled', children: [
        { id: 101, name: '啤酒', level: 2, status: 'enabled' },
        { id: 102, name: '葡萄酒', level: 2, status: 'enabled' }
      ]},
      { id: 2, name: '其它', level: 1, status: 'enabled' },
      { id: 3, name: '食品', level: 1, status: 'enabled', children: [
        { id: 301, name: '调味品', level: 2, status: 'enabled' },
        { id: 302, name: '进口食品', level: 2, status: 'enabled' },
        { id: 303, name: '零食', level: 2, status: 'enabled' }
      ]},
      { id: 4, name: '饮料', level: 1, status: 'enabled', children: [
        { id: 401, name: '果汁', level: 2, status: 'enabled' },
        { id: 402, name: '矿泉水', level: 2, status: 'enabled' },
        { id: 403, name: '乳品', level: 2, status: 'enabled' }
      ]}
    ])

    // 弹窗相关
    const showDialog = ref(false)
    const dialogTitle = ref('新增商品类别')
    const categoryForm = reactive({
      id: null,
      parentId: null,
      name: ''
    })
    const formRules = reactive({
      name: [
        { required: true, message: '请输入类别名称', trigger: 'blur' }
      ]
    })
    const categoryFormRef = ref(null)

    // 计算属性
    const filteredCategories = computed(() => {
      return categories.filter(category => {
        // 搜索过滤
        const nameMatch = category.name.toLowerCase().includes(searchQuery.value.toLowerCase())
        
        // 状态过滤
        let statusMatch = true
        if (statusFilter.value !== 'all') {
          statusMatch = category.status === statusFilter.value
        }
        
        return nameMatch && statusMatch
      })
    })

    const parentCategories = computed(() => {
      return categories.filter(category => category.level === 1)
    })

    // 方法
    const handleSearch = () => {
      currentPage.value = 1
    }

    const refreshData = () => {
      // 模拟刷新数据
      ElMessage.success('数据已刷新')
    }

    const showAddDialog = () => {
      dialogTitle.value = '新增商品类别'
      categoryForm.id = null
      categoryForm.parentId = null
      categoryForm.name = ''
      showDialog.value = true
    }

    const handleEdit = (row) => {
      dialogTitle.value = '编辑商品类别'
      categoryForm.id = row.id
      categoryForm.parentId = row.parentId || null
      categoryForm.name = row.name
      showDialog.value = true
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm('确定要删除该类别吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际项目中这里应该是调用API删除
        const index = categories.findIndex(c => c.id === row.id)
        if (index !== -1) {
          categories.splice(index, 1)
          ElMessage.success('删除成功')
        }
      }).catch(() => {
        // 用户取消删除
      })
    }

    const handleStatusChange = (row) => {
      // 实际项目中这里应该是调用API更新状态
      ElMessage.success(`类别"${row.name}"已${row.status === 'enabled' ? '启用' : '禁用'}`)
    }

    const handleSelectionChange = (selection) => {
      selectedCategories.value = selection
    }

    const handleDisable = () => {
      if (selectedCategories.value.length === 0) {
        ElMessage.warning('请至少选择一个类别')
        return
      }
      // 批量禁用逻辑
      selectedCategories.value.forEach(category => {
        category.status = 'disabled'
      })
      ElMessage.success(`已禁用${selectedCategories.value.length}个类别`)
      selectedCategories.value = []
    }

    const handleEnable = () => {
      if (selectedCategories.value.length === 0) {
        ElMessage.warning('请至少选择一个类别')
        return
      }
      // 批量启用逻辑
      selectedCategories.value.forEach(category => {
        category.status = 'enabled'
      })
      ElMessage.success(`已启用${selectedCategories.value.length}个类别`)
      selectedCategories.value = []
    }

    const handleSubmit = () => {
      categoryFormRef.value.validate(valid => {
        if (valid) {
          if (categoryForm.id) {
            // 编辑逻辑
            const index = categories.findIndex(c => c.id === categoryForm.id)
            if (index !== -1) {
              categories[index].name = categoryForm.name
              categories[index].parentId = categoryForm.parentId
              ElMessage.success('修改成功')
            }
          } else {
            // 新增逻辑
            const newId = Math.max(...categories.map(c => c.id), 0) + 1
            const newCategory = {
              id: newId,
              name: categoryForm.name,
              parentId: categoryForm.parentId,
              level: categoryForm.parentId ? 2 : 1,
              status: 'enabled'
            }
            
            if (categoryForm.parentId) {
              // 添加到子类别
              const parent = categories.find(c => c.id === categoryForm.parentId)
              if (parent) {
                if (!parent.children) {
                  parent.children = []
                }
                parent.children.push(newCategory)
              }
            } else {
              // 添加为一级类别
              categories.push(newCategory)
            }
            
            ElMessage.success('添加成功')
          }
          showDialog.value = false
        }
      })
    }

    return {
      activeTab,
      searchQuery,
      statusFilter,
      currentPage,
      pageSize,
      totalItems,
      categories,
      filteredCategories,
      parentCategories,
      showDialog,
      dialogTitle,
      categoryForm,
      formRules,
      categoryFormRef,
      handleSearch,
      refreshData,
      showAddDialog,
      handleEdit,
      handleDelete,
      handleStatusChange,
      handleSelectionChange,
      handleDisable,
      handleEnable,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.category-management {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.nav-tabs {
  margin-bottom: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.search-input {
  width: 200px;
  margin-right: 10px;
}

.status-select {
  width: 150px;
  margin-right: 10px;
}

.category-table {
  flex: 1;
  overflow: auto;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>